﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LinkCard.Dao;
using LinkCard.Model;
using LinkCard.Utils;
using Newtonsoft.Json;
using System.Data;

namespace LinkCard.ShopCP.Sell
{
    public partial class Sell : System.Web.UI.Page
    {
        public Int64 iSupplierID = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USER"] == null)
            {
                Response.Redirect("~/login.aspx");
            }
            if (!IsPostBack)
            {
                //LoadDeal();
                //LoadDealDetails();
                ddlBuyType.Items.Insert(0, new ListItem("Giảm giá", "1"));
                ddlBuyType.Items.Insert(1, new ListItem("Nguyên giá", "0"));


            }
            //else
            //{
            //    LoadDealDetails();
            //}
            iSupplierID = getSupplierID();
            GetPercentInfo();
        }

        //Lấy thông tin về điểm của Customer
        [System.Web.Services.WebMethod]
        public static string GetCustomerInfo(string sCardNumber)
        {
            try
            {
                //var iCardNumber = Convert.ToInt64(sCardNumber);
                TopLinkEntities db = new TopLinkEntities();
                var customerInfo = db.Customers.Where(t => t.CardNumber == sCardNumber).FirstOrDefault();

                if (customerInfo != null)
                {
                    if (customerInfo.Status == 2)
                    {
                        var wrapper = new
                        {
                            customerPoint = customerInfo.Point.ToString(),
                            customerName = customerInfo.Fullname.ToString(),
                            cardLevel = customerInfo.CardLevel.ToString(),
                            status = 0
                        };
                        //context.Response.Write(JsonConvert.SerializeObject(wrapper));
                        return JsonConvert.SerializeObject(wrapper);
                    }

                    else
                    {
                        var wrapper = new
                        {
                            customerPoint = "",
                            customerName = "",
                            cardLevel = "",
                            status = -1
                        };
                        //context.Response.Write(JsonConvert.SerializeObject(wrapper));
                        return JsonConvert.SerializeObject(wrapper);
                    }
                        
                }
                else
                {
                    var wrapper = new
                    {
                        customerPoint = "",
                        customerName = "",
                        cardLevel = "",
                        status = -2
                    };
                    //context.Response.Write(JsonConvert.SerializeObject(wrapper));
                    return JsonConvert.SerializeObject(wrapper);
                }
            }
            catch
            {
                var wrapper = new
                {
                    customerPoint = "",
                    customerName = "",
                    cardLevel = "",
                    status = -3
                };
                //context.Response.Write(JsonConvert.SerializeObject(wrapper));
                return JsonConvert.SerializeObject(wrapper);
            }
            
        }

        //Lấy về giá trị Điểm thành Tiền
        [System.Web.Services.WebMethod]
        public static string GetConfig()
        {
            try
            {
                //var iCardNumber = Convert.ToInt64(sCardNumber);
                TopLinkEntities db = new TopLinkEntities();
                var configPoint = (from q in db.Config orderby q.Version descending select q).Take(1).FirstOrDefault();

                if (configPoint != null)
                {
                    return configPoint.PointToMoney.ToString();
                }
                else
                    return "-1";
            }
            catch
            {
                return "-2";
            }
        }

        [System.Web.Services.WebMethod]
        public static string LoadPrice(string supplierID, string sPrice, string iPaymentType, string thelevel)
        {
            double dDiscountPercent = 0;
            string priceAfterDiscount = "";
            int nPointTemp = 0; // Số tích lũy được
            try
            {
                string sSQL = "";
                if (thelevel == "Gold")
                {
                    if (iPaymentType == "0")
                    {
                        sSQL = "Select PricePercent as DiscountPercent, PointPercent from supplier where supplierID = " + supplierID.ToString();
                    }
                    else
                    {
                        sSQL = "Select DiscountPercent, PointPercent from supplier where supplierID = " + supplierID.ToString();
                    }
                }
                if (thelevel == "Diamond")
                {
                    if (iPaymentType == "0")
                    {
                        sSQL = "Select DiamondPricePercent as DiscountPercent, DiamondPointPercent as PointPercent from supplier where supplierID = " + supplierID.ToString();
                    }
                    else
                    {
                        sSQL = "Select DiamondDiscountPercent as DiscountPercent, DiamondPointPercent as PointPercent from supplier where supplierID = " + supplierID.ToString();
                    }
                }
                if (thelevel == "Platinum")
                {
                    if (iPaymentType == "0")
                    {
                        sSQL = "Select PlatinumPricePercent as DiscountPercent, PlatinumPointPercent as PointPercent from supplier where supplierID = " + supplierID.ToString();
                    }
                    else
                    {
                        sSQL = "Select PlatinumDiscountPercent as DiscountPercent, PlatinumPointPercent as PointPercent from supplier where supplierID = " + supplierID.ToString();
                    }
                }
                DataTable dt = LinkCard.AdminCP.Common.DataHelper.SelectTable(sSQL, false);

                //decimal nPrice = Convert.ToDecimal(this.price.Value.Trim());
                decimal nPrice = Convert.ToDecimal(sPrice);

                //ConvertUtility.ToDecimal(dt.Rows[0]["Price"]);
                dDiscountPercent = ConvertUtility.ToDouble(dt.Rows[0]["DiscountPercent"]);

                //this.price.Value = Utility.sDecimal(nPrice);
                //this.discounting.Value = Utility.sDoubleOne(dDiscountPercent);
                var dPriceAfterDiscount = ConvertUtility.ToDecimal(nPrice - (nPrice * Convert.ToDecimal(dDiscountPercent / 100)));
                

                #region Công thức cũ
                // điểm = (giá sau chiết khấu * % tích điểm) / tỉ lệ điểm thành tiền trong config

                //Lấy Config
                //var configPointToMoney = 0;
                //try
                //{
                //    //var iCardNumber = Convert.ToInt64(sCardNumber);
                //    TopLinkEntities db = new TopLinkEntities();
                //    var configPoint = (from q in db.Config orderby q.Version descending select q).Take(1).FirstOrDefault();

                //    if (configPoint != null)
                //    {
                //        configPointToMoney = (int)configPoint.PointToMoney;
                //    }
                //    else
                //        configPointToMoney = -1;
                //}
                //catch
                //{
                //    configPointToMoney = -2;
                //}

                //var pointPercent = ConvertUtility.ToDecimal(dt.Rows[0]["PointPercent"]);
                //nPointTemp = ConvertUtility.ToInt32(Math.Floor((dPriceAfterDiscount * pointPercent / 100) / configPointToMoney));
                #endregion

                #region Công thức mới
                // điểm = giá sau chiết khấu / tỉ lệ điểm thưởng trong table Đối tác theo hạng thẻ
                // làm tròn xuống
                decimal pointPercent = 0;
                if (thelevel == "Gold")
                {
                    pointPercent = ConvertUtility.ToDecimal(dt.Rows[0]["PointPercent"]);
                }
                if (thelevel == "Diamond")
                {
                    pointPercent = ConvertUtility.ToDecimal(dt.Rows[0]["PointPercent"]);
                }
                if (thelevel == "Platinum")
                {
                    pointPercent = ConvertUtility.ToDecimal(dt.Rows[0]["PointPercent"]);
                }

                if (pointPercent != 0)
                    nPointTemp = ConvertUtility.ToInt32(Math.Floor(dPriceAfterDiscount / pointPercent));
                else
                    nPointTemp = 0;

                #endregion

                //txtPointTemp.Value = nPointTemp.ToString();

                //return new string[]{
                //    dDiscountPercent.ToString(),
                //    priceAfterDiscount,
                //    nPointTemp.ToString()
                //};

                priceAfterDiscount = Utility.sDecimal(dPriceAfterDiscount);
            }
            catch
            {
                //errorMessage.Visible = true;
            }


            //string json = "{ 'dDiscountPercent':" + dDiscountPercent.ToString() + ", priceAfterDiscount': " + priceAfterDiscount + ", 'priceAfterDiscount':" + nPointTemp.ToString() + "}";
            //context.Response.Write(json);
            var wrapper = new
            {
                dDiscountPercent = dDiscountPercent.ToString(),
                priceAfterDiscount = priceAfterDiscount.ToString(),
                nPointTemp = nPointTemp.ToString()
            };
            string returnJson = JsonConvert.SerializeObject(wrapper);
            return returnJson;
        }

        private void LoadDealDetails()
        {
            try
            {
                //if (this.ddlDeal.SelectedValue != null)
                //{
                var supplierID = getSupplierID();
                int iPaymentType = ConvertUtility.ToInt32(ddlBuyType.SelectedValue);
                //var iDealID = Convert.ToInt64(this.ddlDeal.SelectedValue.ToString());
                string sSQL ="";
                if (iPaymentType == 0)
                {
                    sSQL = "Select 0 as DiscountPercent, PointPercent from supplier where supplierID = " + supplierID.ToString();
                }
                else
                {
                    sSQL = "Select DiscountPercent, PointPercent from supplier where supplierID = " + supplierID.ToString();

                }
                DataTable dt = LinkCard.AdminCP.Common.DataHelper.SelectTable(sSQL, false);

                decimal nPrice = Convert.ToDecimal(this.price.Value.Trim());
                    //ConvertUtility.ToDecimal(dt.Rows[0]["Price"]);
                double dDiscountPercent = ConvertUtility.ToDouble(dt.Rows[0]["DiscountPercent"]);
                this.price.Value = Utility.sDecimal(nPrice);
                this.discounting.Value = Utility.sDoubleOne(dDiscountPercent);
                this.txtPriceAfter.Value = Utility.sDecimal(ConvertUtility.ToDecimal(nPrice - (nPrice * Convert.ToDecimal(dDiscountPercent / 100))));
                    
                PointPercent.Value = dt.Rows[0]["PointPercent"].ToString();

                int nPointTemp = 0; // Số tích lũy được
                nPointTemp = ConvertUtility.ToInt32(Math.Floor(ConvertUtility.ToDecimal(nPrice - (nPrice * Convert.ToDecimal(dDiscountPercent / 100))) * ConvertUtility.ToDecimal(dt.Rows[0]["PointPercent"]) / 100));
                txtPointTemp.Value = nPointTemp.ToString();

                //}
            }
            catch
            {
                errorMessage.Visible = true;
            }
        }

        protected Int64 getSupplierID()
        {
            try
            {

                if (Convert.ToInt32(Session["SHOPADMIN"]) == 1) // quanr ly cua hang
                {
                    Session["SupplierID"] = ConvertUtility.ToInt64(Session["USER"]);
                    return ConvertUtility.ToInt64(Session["USER"]);
                }
                else if (Convert.ToInt32(Session["SHOPADMIN"]) == 0)
                {
                    DataTable dt = LinkCard.AdminCP.Common.DataHelper.SelectTable("SELECT SupplierID FROM [ShopStaff] WHERE Username ='" + Session["USER"].ToString() + "'", false);
                    if (dt.Rows.Count > 0)
                    {
                        Session["SupplierID"] = ConvertUtility.ToInt64(dt.Rows[0]["SupplierID"]);
                        return ConvertUtility.ToInt64(dt.Rows[0]["SupplierID"]);
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch
            {
                return 0;
            }
        }

        protected Int64 getCustomerID()
        {
            DataTable dt = LinkCard.AdminCP.Common.DataHelper.SelectTable("SELECT CustomerID from Customer WHERE Cardnumber ='" + sCardNumber.Value.Trim() + "'", false);
            if (dt.Rows.Count > 0)
            {
                return ConvertUtility.ToInt64(dt.Rows[0]["CustomerID"]);
            }
            else
            {
                return 0;
            }

        }

        protected void GetPercentInfo()
        {
            try
            {
                
                var db = new TopLinkEntities();

                var table = db.Supplier.Where(t => t.SupplierID == iSupplierID).FirstOrDefault();

                this.goldSaleOffPercent.Text = table.DiscountPercent.ToString() + " %";
                this.goldPercent.Text = table.PricePercent.ToString() + " %";
                //this.diamondPercent.Text = table.DiamondDiscountPercent.ToString() + " %";
                //this.platinumPercent.Text = table.PlatinumDiscountPercent.ToString() + " %";

                this.goldPoint.Text = Utility.sDecimal(Convert.ToDecimal(table.PointPercent)) + " VND / điểm";
                //this.diamondPoint.Text = Utility.sDecimal(Convert.ToDecimal(table.DiamondPointPercent)) + " VND / điểm";
                //this.platinumPoint.Text = Utility.sDecimal(Convert.ToDecimal(table.PlatinumPointPercent)) + " VND / điểm";
            }
            catch
            {
                
            }
        }

        protected void btnPay_Click(object sender, EventArgs e)
        {
            //Utils.SMSTool.SendSMS();
            try
            {
                int nPointTemp = 0; // Số tích lũy được
                string cusPhoneNumber = "";
                string cusPoint = "";

                Int64 nCustomerID = 0;
                nPointTemp = ConvertUtility.ToInt32(txtPointTemp.Value);
                nCustomerID = getCustomerID();
                var db = new TopLinkEntities();
                //Luu vao PayLog
                var dao = new PayLogDao();
                var _Payment = new LinkCard.Model.PayLog();
                _Payment.SupplierID = getSupplierID();
                _Payment.CustomerID = nCustomerID;

                _Payment.PayPointAdd = nPointTemp; //điểm tích luỹ đc
                _Payment.PayPriceAfterDis = ConvertUtility.ToDecimal(txtPriceAfter.Value);
                _Payment.PayPrice = ConvertUtility.ToDecimal(price.Value);
                _Payment.PayDate = DateTime.Now;
                _Payment.PayDiscountPercent = ConvertUtility.ToDecimal(this.discounting.Value);
                _Payment.BuyMethod = ConvertUtility.ToByte(ddlBuyType.SelectedValue);
                _Payment.PayMethod = ConvertUtility.ToByte(PayMethod.Value); //0:tien mat, 1: the ngan hang, 2: doi diem
                _Payment.PayAmount = ConvertUtility.ToDecimal(PaymentAmount.Value);
                _Payment.CustomerPointBefore = ConvertUtility.ToInt64(this.customerPoint.Value.Trim());
                _Payment.Status = 0; //Status = 0: thanh cong, 1: Canceled, 2-> dung sau nay

                dao.Add(_Payment);
                Int64 nPaymentID = _Payment.PayID;

                Customer _customer = new Customer();
                _customer = db.Customers.FirstOrDefault(t => t.CustomerID == nCustomerID);

                // Cộng điểm cho khách hàng sau khi thanh toán thành công
                _customer.Point += nPointTemp;
                //Lấy số điện thoại để sms
                cusPhoneNumber = _customer.MobilePhone;

                //Trừ điểm khách hàng nếu thanh toán bằng điểm LinkCard
                if (ConvertUtility.ToByte(PayMethod.Value) == 2)
                {
                    _customer.Point = _customer.Point - ConvertUtility.ToInt32(PaymentAmount.Value);
                }
                
                //Lấy ra điểm sau thanh toán
                cusPoint = _customer.Point.ToString();

                db.SaveChanges();

                //Lưu log
                Int64 shopStaffID = 0;
                if (Session["ShopStaffID"] != "")
                    shopStaffID = Convert.ToInt64(Session["ShopStaffID"].ToString());
                var logAction = LogActions.LogItem(0, getSupplierID(), nPaymentID, nCustomerID, shopStaffID, "Bán hàng", "Sell", "ShopCP");

                //Gửi tin nhắn
                if ((cusPhoneNumber != "") && cusPhoneNumber.Length >= 10)
                {
                    Int64 _kqSMS = Utils.SMSTool.SendSMS(cusPhoneNumber, "Cam on Khach hang da su dung dich vu. Diem tich luy hien co la: " + cusPoint);
                    if (_kqSMS < 0) //nếu nhắn tin lỗi thì log lại lỗi, nhắn ok thì thôi ko lưu lại nữa
                    {
                        var logSMS = LogActions.LogItem(0, getSupplierID(), nPaymentID, nCustomerID, shopStaffID, "Lỗi nhắn tin: " + _kqSMS.ToString(), "Sell", "ShopCP");
                    }
                }
                Response.Redirect("SellSucc.aspx?view=Succ&PayLogID=" + nPaymentID, true);
            }
            catch (Exception ex)
            {
                errorMessage.Visible = true;
            }
        }

        protected void btnCalPrice_Click(object sender, EventArgs e)
        {
            LoadDealDetails();
        }

        
    }
}